package com.service.impl.user;

import com.core.dto.AccountDTO;
import com.core.model.lxf.Account;
import com.core.model.lxf.AccountTransferDetails;
import com.dao.AccountDao;
import com.service.user.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/12/30
 * Time: 16:49
 * To change this template use Editor | File and Code Templates.
 */
@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public boolean transferToAccount(String sourceAccountId, String targetAccountId, String amount) {
        Account source = accountDao.findByGuid(Account.class, sourceAccountId);
        Account target = accountDao.findByGuid(Account.class, targetAccountId);
        boolean result = false;
        try {
            result = source.transferTo(target, Double.parseDouble(amount));
            System.out.println("transfer services success");
            return true;
        } finally {
            AccountTransferDetails details = new AccountTransferDetails(source, target, Double.parseDouble(amount), result);
            saveTransferResult(details);
            System.out.println("save details success");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveTransferResult(AccountTransferDetails details) {
        accountDao.saveOrUpdate(details);
    }

    @Override
    public void saveAccount(AccountDTO accountDTO) {
        Account account = accountDTO.toAccount(accountDTO);
        accountDao.saveOrUpdate(account);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public AccountDTO findAccountByGuid(String accountGuid) {
        Account account = accountDao.findByGuid(Account.class, accountGuid);
        return AccountDTO.toDTO(account);
    }

}
